package xyz.xuanlee.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import xyz.xuanlee.springcloud.entities.CommonResult;
import xyz.xuanlee.springcloud.entities.Payment;
import xyz.xuanlee.springcloud.loadbalancer.IMyLoadBalancer;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {

    public static final String PAYMENT_BASE_URL = "http://CLOUD-PAYMENT-SERVICE";
    @Resource
    public IMyLoadBalancer loadBalancer;
    @Resource
    public DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/consumer/payment/create")
    public CommonResult<Integer> create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_BASE_URL + "/payment/create",
                payment,
                CommonResult.class);
    }

    @GetMapping("/consumer/payment/getById/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_BASE_URL + "/payment/getPayment/" + id,
                CommonResult.class);
    }

    @GetMapping("/consumer/lb")
    public CommonResult<String> testMyLoadBalancer() {
        ServiceInstance instance = loadBalancer.selectService(discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"));
        String uri = instance.getUri().toString();
        ResponseEntity<CommonResult> resp = restTemplate.getForEntity(uri + "/payment/port", CommonResult.class);
        log.info("status code: " + resp.getStatusCode());
        return resp.getBody();
    }
}
